package cj.web.admin.controllers;

import java.io.File;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.constants.CategoryEnum;
import cj.web.admin.constants.IndustryCategoryEnum;
import cj.web.admin.constants.MemuEnum;
import cj.web.admin.constants.SourceEnum;
import cj.web.admin.dao.ContantDAO;
import cj.web.admin.dao.IndustryDAO;
import cj.web.admin.domain.Industry;
import cj.web.login.controllers.BaseController;

@Path("/industry")
public class IndustryController extends BaseController{

	private static Logger logger = Logger.getLogger(IndustryController.class.getName());
	
	@Autowired
	private IndustryDAO industryDao;
	@Autowired
	private ContantDAO contantDao;

	@Get("show")
	public String show(Model model, @Param("category")String category){
		model.add("categoryEnum", EnumSet.allOf(IndustryCategoryEnum.class) );
		model.add("category",category);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(category));
		return "portal/industryList.vm";
	}
	
	@Get("showJf")   //长江金服 新闻列表
	public String showJf(Model model){
		String category = String.valueOf(IndustryCategoryEnum.CJJF_XW.getValue());
		model.add("category", category);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(category));
		return "finance/financeList.vm";
	}
	
	@Post("list")
	public String list(Industry industry){
		JSONObject jo = new JSONObject();
		
		List<Industry> objs = industryDao.list(industry);
		int size = industryDao.size(industry);
		
		jo.put("data", objs);
		jo.put("draw", industry.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		
		return "@" + jo.toString();
	}
	
	@Get("createPage")  
	public String createPage(Model model,Industry industry, @Param("category")String category)
	{
		model.add("categoryEnum", EnumSet.allOf(IndustryCategoryEnum.class) );
		model.add("category",category);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(category));
		return "portal/industryDetail.vm";
	}
	
	@Get("createJfNews") //长江金服 新建新闻
	public String createJfNews(Model model)
	{
		String category = String.valueOf(IndustryCategoryEnum.CJJF_XW.getValue());
		model.add("category",category);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(category));
		return "finance/financeDetail.vm";
	}
	
	@Post("create")
	public String create(Industry industry,HttpServletRequest request)
	{
		industry.setCreateUser(returnSessionObj(request).getAccount());
		industry.setCreateAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
		industry.setUpdateUser(returnSessionObj(request).getAccount());
		industry.setUpdateAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
		industry.setReleaseAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
		industry.setReleaseState(Constants.portal.releaseState.state_1);
		industry.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag",Constants.returnObj.returnFlag_true);
		
		try{
			industryDao.create(industry);
		}
		catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id)
	{
		model.add("categoryEnum", EnumSet.allOf(IndustryCategoryEnum.class) );
		
		Industry industry = industryDao.queryById(id);
		model.add("industry", industry);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(industry.getCategory()));
		return "portal/industryEdit.vm";
	}
	
	@Get("editJfNews") //长江金服 编辑新闻
	public String editJfNews(Model model,@Param("id") int id)
	{
		Industry industry = industryDao.queryById(id);
		model.add("industry", industry);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(industry.getCategory()));
		return "finance/financeEdit.vm";
	}
	
	@Post("update")
	public String update(Industry industry, HttpServletRequest request){
		industry.setUpdateUser(returnSessionObj(request).getAccount());
		industry.setUpdateAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag",Constants.returnObj.returnFlag_true);
		
		try{
			industryDao.update(industry);
		}
		catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id)
	{
		Industry obj = industryDao.queryById(id);
		if(obj != null){
			industryDao.deleteById(id);
		}
		
		return "r:show?category=" + obj.getCategory();
	}
	
	@Post("upload")
	public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                ImageUtils.scale2(path+"/"+fileName, path+"/s_"+fileName, 300, 300, true);//缩率图
                
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	//置顶
	@Get("stick")
    public String stick(@Param("id") int id) {
		industryDao.updateByStickTime(id);
		return "r:show";
	}
	
	//取消置顶
	@Get("cancelStick")
    public String cancelStick(@Param("id") int id) {
		industryDao.updateByStickTimeIsNull(id);
		return "r:show";
	}
	
	@Get("stickJf")       //长江金服 置顶
    public String stickJf(@Param("id") int id) {
		JSONObject jo = new JSONObject();
		industryDao.updateByStickTime(id);
		return "@" + jo.toString();
	}
	
	@Get("cancelStickJf") //长江金服 取消置顶
    public String cancelStickJf(@Param("id") int id) {
		JSONObject jo = new JSONObject();
		industryDao.updateByStickTimeIsNull(id);
		return "@" + jo.toString();
	}
	
	@Get("deleteJf")      //长江金服 删除
	public String deleteJf(Model model,@Param("id") int id)
	{
		JSONObject jo = new JSONObject();
		Industry obj = industryDao.queryById(id);
		if(obj != null){
			industryDao.deleteById(id);
		}
		return "@" + jo.toString();
	}
	
	@Post("uploadJf")       //长江金服 图片上传
	public String uploadJf(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (file != null && !file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                ImageUtils.scale2(path+"/"+fileName, path+"/s_"+fileName, 400, 750, true);//缩率图
                
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	@Get("copyById")
	public String copyById(Model model,@Param("id") int id)
	{
		model.add("categoryEnum", EnumSet.allOf(CategoryEnum.class) );
		
		Industry industry = industryDao.queryById(id);
		model.add("industry", industry);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(industry.getCategory()));
		return "portal/industryCopy.vm";
	}
	
	@Post("copyToPortal")
	public String copyToPortal(@Param("id")int id, @Param("category")int category){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		int source = SourceEnum.CJKD.getValue();
		contantDao.copyFromIndustry(id, category, source);
		
		return "@" + jo.toString();
	}
	
	/**
	 * 返回菜单
	 * @param category
	 * @return
	 */
	private MemuEnum retMemuValue(String type)
	{
		
		if(type.equals("0"))
		{
			return MemuEnum.ywgsdt;
		}
		if(type.equals("1"))
		{
			return MemuEnum.ywgsdt;
		}
		if(type.equals("2"))
		{
			return MemuEnum.kdgsgsxw;
		}
		if(type.equals("3"))
		{
			return MemuEnum.kdgszxhd;
		}
		if(type.equals("4"))
		{
			return MemuEnum.kdgshydt;
		}
		if(type.equals("5"))
		{
			return MemuEnum.kdgsnrbj;
		}
		if(type.equals("6"))
		{
			return MemuEnum.cjjfNews;
		}
		return null;
	}
}
